package com.langshixiaobai.game;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.langshixiaobai.eneity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

//处理大厅匹配请求
@Component
public class Matcher {

    //匹配队列
    private Queue<User> normalQueue = new LinkedList<>();

    private Queue<User> highQueue = new LinkedList<>();

    private Queue<User> hardQueue = new LinkedList<>();


    //TODO 重新创建了，导致值被覆盖
    @Autowired
    private OnlineUserMap onlineUserMap;


    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RoomManager roomManager ;


    // 创建相应扫描线程，进行循环处理，如果符合处理条件，进行处理
    public Matcher() {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(hardQueue);
                }
            }
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }


    //玩家加入匹配
    public void addUser(User user) {
        if (user.getScore() < 2000) {
            //加锁避免线程安全问题，不同队列不需要加锁
            synchronized (normalQueue) {
                System.out.println("把玩家: " + user.getUsername() + "加入normalQueue");
                normalQueue.offer(user);
                normalQueue.notify();
            }
        } else if (user.getScore() >= 2000 && user.getScore() <= 3000) {
            synchronized (highQueue) {
                System.out.println("把玩家: " + user.getUsername() + "加入highQueue");
                highQueue.offer(user);
                hardQueue.notify();
            }
        } else {
            synchronized (hardQueue) {
                System.out.println("把玩家: " + user.getUsername() + "加入hardQueue");
                hardQueue.offer(user);
                hardQueue.notify();
            }
        }
    }

    //玩家停止匹配
    public void removeUser(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                System.out.println("把玩家: " + user.getUsername() + "移除normalQueue");
                normalQueue.remove(user);
                normalQueue.notify();
            }
        } else if (user.getScore() >= 2000 && user.getScore() <= 3000) {
            synchronized (highQueue) {
                System.out.println("把玩家: " + user.getUsername() + "移除highQueue");
                highQueue.remove(user);
                highQueue.notify();
            }
        } else {
            synchronized (hardQueue) {
                System.out.println("把玩家: " + user.getUsername() + "移除hardQueue");
                hardQueue.remove(user);
                hardQueue.notify();
            }
        }
    }



    //处理匹配
    public void handlerMatch(Queue<User> matchQueue) {
        try {
            synchronized (matchQueue) {

                while (matchQueue.size() < 2) {
                    //堵塞等待，防止cpu空转，当不满足条件是进行堵塞等待
                    matchQueue.wait();
                }
                User user1 = matchQueue.poll();
                User user2 = matchQueue.poll();
                System.out.println("玩家1信息: " + user1);
                System.out.println("玩家2信息：" + user2);
                WebSocketSession session1 = onlineUserMap.getFromGameHall(user1.getUserId());
                WebSocketSession session2 = onlineUserMap.getFromGameHall(user2.getUserId());
                if (session1 == null) {
                    //如果玩家1下线需要把玩家2重新放入匹配队列
                    matchQueue.offer(user2);
                    System.out.println("session1 为空");
                    return;
                }
                if (session2 == null) {
                    //如果玩家2下线，需要把玩家1重新放入匹配对了
                    matchQueue.offer(user1);
                    System.out.println("session2 为空");
                    return;
                }
                //如果是一个用户多开，需要将一个重新放入 队列，另一个抛弃
                if (session1 == session2) {
                    matchQueue.offer(user1);
                    System.out.println("session1 == session2");
                    return;
                }

                MessageResponse response1 = new MessageResponse();
                MessageResponse response2 = new MessageResponse();
                //创建房间
                Room room = new Room();
                //将房间信息添加到房间管理器里

                roomManager.addRoom(room, user1.getUserId(), user2.getUserId());

                // 匹配成功后，应该向双方发送消息
                response1.setOK(true);
                response1.setMessage("matchSuccess");
                System.out.println("客户端1匹配成功");
                session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(response1)));
                response2.setOK(true);
                response2.setMessage("matchSuccess");
                System.out.println("客户端2匹配成功");
                session2.sendMessage(new TextMessage(objectMapper.writeValueAsString(response2)));
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
